﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Kiiro.Common.Entities;

namespace Kiiro.Common.Utility
{
    public static class SPDataHelpers
    {
        #region DataRowPropertyHelpers

        private static string GetStringValue ( DataRow dataRow, string fieldName )
        {
            string value = default ( string );
            if ( dataRow.Table.Columns.Contains ( fieldName ) )
            {
                object objValue = dataRow [ fieldName ];
                value = objValue != null && objValue.ToString ( ) != "" ? objValue.ToString ( ) : default ( string );
            }
            return value;
        }

        private static int GetLookupSingleIntValue ( DataRow dataRow, string fieldName )
        {
            List<string> lookupValues = GetListOfStringsValue ( dataRow, fieldName );
            return lookupValues.Count > 0 ? int.Parse ( lookupValues [ 0 ] ) : default ( int );
        }

        private static string GetLookupSingleStringValue ( DataRow dataRow, string fieldName )
        {
            List<string> lookupValues = GetListOfStringsValue ( dataRow, fieldName );
            return lookupValues.Count > 0 ? lookupValues [ 1 ] : default ( string );
        }

        private static List<string> GetListOfStringsValue ( DataRow dataRow, string fieldName )
        {
            string value = GetStringValue ( dataRow, fieldName );
            return !string.IsNullOrEmpty ( value ) ? FormattingHelpers.FieldTextToListOfStrings ( value ) : new List<string> ( );
        }

        private static List<string> GetListOfMuliStringsValue ( DataRow dataRow, string fieldName )
        {
            List<string> listOfEmails = new List<string> ( );
            string value = GetStringValue ( dataRow, fieldName );
            List<string> listOfStrings = !string.IsNullOrEmpty ( value ) ? FormattingHelpers.FieldTextToListOfStrings ( value ) : new List<string> ( );

            bool second = false;
            foreach ( string str in listOfStrings )
            {
                if ( second )
                {
                    listOfEmails.Add ( str );
                    second = false;
                }
                else
                {
                    second = true;
                }
            }
            return listOfEmails;
        }

        private static List<int> GetListOfIntsValue ( DataRow dataRow, string fieldName )
        {
            List<int> listOfInts = new List<int> ( );
            string value = GetStringValue ( dataRow, fieldName );
            List<string> listOfStrings = !string.IsNullOrEmpty ( value ) ? FormattingHelpers.FieldTextToListOfStrings ( value ) : new List<string> ( );

            foreach ( string str in listOfStrings )
            {
                listOfInts.Add ( Convert.ToInt32 ( str ) );
            }
            return listOfInts;
        }

        private static float GetFloatValue ( DataRow dataRow, string fieldName )
        {
            float value = default ( float );
            if ( dataRow.Table.Columns.Contains ( fieldName ) )
            {
                object objValue = dataRow [ fieldName ];
                value = objValue != null && objValue.ToString ( ) != "" ? float.Parse ( objValue.ToString ( ) ) : default ( float );
            }
            return value;
        }

        private static int GetIntegerValue ( DataRow dataRow, string fieldName )
        {
            return Convert.ToInt32 ( GetFloatValue ( dataRow, fieldName ) );
        }

        private static bool GetBooleanValue ( DataRow dataRow, string fieldName )
        {
            bool value = false;
            if ( dataRow.Table.Columns.Contains ( fieldName ) )
            {
                int intValue = GetIntegerValue ( dataRow, fieldName );
                value = intValue == 1;
            }
            return value;
        }

        private static DateTime GetDateTimeValue ( DataRow dataRow, string fieldName )
        {
            DateTime value = default ( DateTime );
            if ( dataRow.Table.Columns.Contains ( fieldName ) )
            {
                object dtValue = dataRow [ fieldName ];
                value = dtValue != null && dtValue.ToString ( ) != "" ? DateTime.Parse ( dtValue.ToString ( ) ) : default ( DateTime );
            }
            return value;
        }

        private static Guid GetGuidValue ( DataRow dataRow, string fieldName )
        {
            string value = GetStringValue ( dataRow, fieldName );
            return !string.IsNullOrEmpty ( value ) ? new Guid ( value ) : default ( Guid );
        }

        private static User GetUserValue ( DataRow dataRow, string fieldName )
        {
            int value = GetIntegerValue ( dataRow, fieldName );

            User user = new User ( );
            user.Id = value;

            return user;
        }

        private static ProjectStatus GetProjectStatusValue ( DataRow dataRow, string fieldName )
        {
            string value = GetStringValue ( dataRow, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( ProjectStatus ) Enum.Parse ( typeof ( ProjectStatus ), value ) : default ( ProjectStatus );
        }

        private static WorkType GetWorkTypeValue ( DataRow dataRow, string fieldName )
        {
            string value = GetStringValue ( dataRow, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( WorkType ) Enum.Parse ( typeof ( WorkType ), value ) : default ( WorkType );
        }

        private static TimeMetric GetTimeMetricValue ( DataRow dataRow, string fieldName )
        {
            string value = GetStringValue ( dataRow, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( TimeMetric ) Enum.Parse ( typeof ( TimeMetric ), value ) : default ( TimeMetric );
        }

        private static Version GetVersionValue ( DataRow dataRow, string fieldName )
        {
            string value = GetStringValue ( dataRow, fieldName );
            return new Version ( value );
        }

        private static StatusType GetStatusTypeValue ( DataRow dataRow, string fieldName )
        {
            string value = GetStringValue ( dataRow, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( StatusType ) Enum.Parse ( typeof ( StatusType ), value ) : default ( StatusType );
        }

        private static ItemType GetItemTypeValue ( DataRow dataRow, string fieldName )
        {
            string value = GetStringValue ( dataRow, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( ItemType ) Enum.Parse ( typeof ( ItemType ), value ) : default ( ItemType );
        }

        private static EventType GetEventTypeValue ( DataRow dataRow, string fieldName )
        {
            string value = GetStringValue ( dataRow, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( EventType ) Enum.Parse ( typeof ( EventType ), value ) : default ( EventType );
        }

        private static double GetDoubleValue ( DataRow dataRow, string fieldName )
        {
            double value = default ( double );
            if ( dataRow.Table.Columns.Contains ( fieldName ) )
            {
                object objValue = dataRow [ fieldName ];
                value = objValue != null && objValue.ToString ( ) != "" ? double.Parse ( objValue.ToString ( ) ) : default ( double );
            }
            return value;
        }

        #endregion

        #region SPListItemPropertyHelpers

        private static string GetStringValue ( SPListItem listItem, string fieldName )
        {
            string str = default ( string );
            try
            {
                object value = listItem [ fieldName ];
                if ( value != null && value.ToString ( ) != "" )
                    str = value.ToString ( );
            }
            catch { }

            return str;
        }

        private static string GetStringValueFromPropertyBag ( SPListItem listItem, string key )
        {
            object value = listItem.Properties [ key ];
            return value != null && value.ToString ( ) != "" ? value.ToString ( ) : default ( string );
        }

        private static int GetLookupSingleIntValue ( SPListItem listItem, string fieldName )
        {
            List<string> lookupValues = GetListOfStringsValue ( listItem, fieldName );
            return lookupValues.Count > 0 ? int.Parse ( lookupValues [ 0 ] ) : default ( int );
        }

        private static string GetLookupSingleStringValue ( SPListItem listItem, string fieldName )
        {
            List<string> lookupValues = GetListOfStringsValue ( listItem, fieldName );
            return lookupValues.Count > 0 ? lookupValues [ 1 ] : default ( string );
        }

        private static List<string> GetListOfStringsValue ( SPListItem listItem, string fieldName )
        {
            string value = GetStringValue ( listItem, fieldName );
            return !string.IsNullOrEmpty ( value ) ? FormattingHelpers.FieldTextToListOfStrings ( value ) : new List<string> ( );
        }

        private static List<string> GetListOfMuliStringsValue ( SPListItem listItem, string fieldName )
        {
            List<string> listOfEmails = new List<string> ( );
            string value = GetStringValue ( listItem, fieldName );
            List<string> listOfStrings = !string.IsNullOrEmpty ( value ) ? FormattingHelpers.FieldTextToListOfStrings ( value ) : new List<string> ( );

            bool second = false;
            foreach ( string str in listOfStrings )
            {
                if ( second )
                {
                    listOfEmails.Add ( str );
                    second = false;
                }
                else
                {
                    second = true;
                }
            }
            return listOfEmails;
        }

        private static List<int> GetListOfIntsValue ( SPListItem listItem, string fieldName )
        {
            List<int> listOfInts = new List<int> ( );
            string value = GetStringValue ( listItem, fieldName );
            List<string> listOfStrings = !string.IsNullOrEmpty ( value ) ? FormattingHelpers.FieldTextToListOfStrings ( value ) : new List<string> ( );

            foreach ( string str in listOfStrings )
            {
                listOfInts.Add ( Convert.ToInt32 ( str ) );
            }
            return listOfInts;
        }

        private static List<KiiroGroup> GetListOfKiiroGroupsValue ( SPListItem listItem, string fieldName )
        {
            List<KiiroGroup> listOfGroups = new List<KiiroGroup> ( );
            string value = GetStringValue ( listItem, fieldName );
            List<string> listOfStrings = !string.IsNullOrEmpty ( value ) ? FormattingHelpers.FieldTextToListOfStrings ( value ) : new List<string> ( );

            foreach ( string str in listOfStrings )
            {
                listOfGroups.Add ( ( KiiroGroup ) Enum.Parse ( typeof ( KiiroGroup ), str, true ) );
            }
            return listOfGroups;
        }

        private static float GetFloatValue ( SPListItem listItem, string fieldName )
        {
            object value = listItem [ fieldName ];
            return value != null && value.ToString ( ) != "" ? float.Parse ( value.ToString ( ) ) : default ( float );
        }

        private static int GetIntegerValue ( SPListItem listItem, string fieldName )
        {
            return Convert.ToInt32 ( GetFloatValue ( listItem, fieldName ) );
        }

        public static bool GetBooleanValue ( SPListItem listItem, string fieldName )
        {
            string value = GetStringValue ( listItem, fieldName );
            return value != null && value.ToString ( ) != "" ? bool.Parse ( value.ToString ( ) ) : default ( bool );
        }

        private static DateTime GetDateTimeValue ( SPListItem listItem, string fieldName )
        {
            object value = listItem [ fieldName ];
            return value != null && value.ToString ( ) != "" ? DateTime.Parse ( value.ToString ( ) ) : default ( DateTime );
        }

        private static Guid GetGuidValue ( SPListItem listItem, string fieldName )
        {
            string value = GetStringValue ( listItem, fieldName );
            return !string.IsNullOrEmpty ( value ) ? new Guid ( value ) : default ( Guid );
        }

        private static User GetUserValue ( SPListItem listItem, string fieldName )
        {
            int value = GetIntegerValue ( listItem, fieldName );

            User user = new User ( );
            user.Id = value;

            return user;
        }

        private static TimeMetric GetTimeMetricValue ( SPListItem listItem, string fieldName )
        {
            string value = GetStringValue ( listItem, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( TimeMetric ) Enum.Parse ( typeof ( TimeMetric ), value ) : default ( TimeMetric );
        }

        private static ProjectStatus GetProjectStatusValue ( SPListItem listItem, string fieldName )
        {
            string value = GetStringValue ( listItem, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( ProjectStatus ) Enum.Parse ( typeof ( ProjectStatus ), value ) : default ( ProjectStatus );
        }

        private static WorkType GetWorkTypeValue ( SPListItem listItem, string fieldName )
        {
            string value = GetStringValue ( listItem, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( WorkType ) Enum.Parse ( typeof ( WorkType ), value ) : default ( WorkType );
        }

        private static Version GetVersionValue ( SPListItem listItem, string fieldName )
        {
            string value = GetStringValue ( listItem, fieldName );
            return new Version ( value );
        }

        private static StatusType GetStatusTypeValue ( SPListItem listItem, string fieldName )
        {
            string value = GetStringValue ( listItem, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( StatusType ) Enum.Parse ( typeof ( StatusType ), value ) : default ( StatusType );
        }

        private static ItemType GetItemTypeValue ( SPListItem listItem, string fieldName )
        {
            string value = GetStringValue ( listItem, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( ItemType ) Enum.Parse ( typeof ( ItemType ), value ) : default ( ItemType );
        }

        private static EventType GetEventTypeValue ( SPListItem listItem, string fieldName )
        {
            string value = GetStringValue ( listItem, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( EventType ) Enum.Parse ( typeof ( EventType ), value ) : default ( EventType );
        }

        private static double GetDoubleValue ( SPListItem listItem, string fieldName )
        {
            object value = listItem [ fieldName ];
            return value != null && value.ToString ( ) != "" ? double.Parse ( value.ToString ( ) ) : default ( double );
        }

        /// <summary>
        /// ONLY USED WHEN HANDLING CUSTOM ITEMS BECAUSE OF THE WAY CREATEDBY AND MODIFIEDBY PROPERTIES
        /// ARE SAVED ON CUSTOM ITEMS. (SHAREPOINT HANDLES THE SAVE)
        /// 
        /// PLEASE DON'T USE THIS METHOD FOR ANYTHING ELSE!
        /// 
        /// Gets a dummy Midori User from SPFieldText. Sets the User.Id = SPUser.Id. 
        ///     IMPORTANT: You must call UserModel.GetUserById ( user.Id, siteCollectionId ) 
        ///     afterwards in order to get the correct Midori User!
        /// </summary>
        public static User GetMidoriUser ( SPListItem listItem, string fieldName )
        {
            User user = new User ( );
            int id = 0;

            List<string> fieldText = GetListOfStringsValue ( listItem, fieldName );
            int.TryParse ( fieldText [ 0 ], out id );
            user.Id = id;

            return user;
        }

        public static void PopulateCustomFieldsInListItemFromEntity ( SPListItem listItem, BaseEntity entity )
        {
            if ( entity.CustomFieldNamesAndValues != null )
            {
                foreach ( string key in entity.CustomFieldNamesAndValues.Keys )
                {
                    listItem [ key ] = entity.CustomFieldNamesAndValues [ key ];
                }
            }
        }

        #endregion

        #region SPItemEventDataCollectionPropertyHelpers

        public static string GetStringValue ( SPItemEventDataCollection eventData, string fieldName )
        {
            object value = eventData [ fieldName ];
            return value != null && value.ToString ( ) != "" ? value.ToString ( ) : default ( string );
        }

        public static bool GetBooleanValue ( SPItemEventDataCollection eventData, string fieldName )
        {
            string value = GetStringValue ( eventData, fieldName );
            return value != null && value.ToString ( ) != "" ? Boolean.Parse ( value.ToString ( ) ) : default ( bool );
        }

        public static ProjectStatus GetProjectStatusValue ( SPItemEventDataCollection eventData, string fieldName )
        {
            string value = GetStringValue ( eventData, fieldName );
            return !string.IsNullOrEmpty ( value ) ? ( ProjectStatus ) Enum.Parse ( typeof ( ProjectStatus ), value ) : default ( ProjectStatus );
        }

        #endregion

        #region Make Comments

        public static Comment MakeComment ( DataRow dataRow )
        {
            Comment comment = new Comment ( );

            comment.CreatedBy = GetUserValue ( dataRow, Constants.CommentFieldNames.CreatedBy );
            comment.CreatedDate = GetDateTimeValue ( dataRow, Constants.CommentFieldNames.CreatedDate );
            comment.Description = GetStringValue ( dataRow, Constants.CommentFieldNames.Description );
            comment.Id = GetIntegerValue ( dataRow, Constants.CommentFieldNames.ItemId );
            comment.IsNew = GetBooleanValue ( dataRow, Constants.CommentFieldNames.IsNew );
            comment.ModifiedBy = GetUserValue ( dataRow, Constants.CommentFieldNames.ModifiedBy );
            comment.ModifiedDate = GetDateTimeValue ( dataRow, Constants.CommentFieldNames.ModifiedDate );
            comment.ServerRelativeUrl = GetStringValue ( dataRow, Constants.CommentFieldNames.ServerRelativeUrl );
            comment.SiteCollectionId = GetGuidValue ( dataRow, Constants.CommentFieldNames.SiteCollectionId );

            comment.Text = GetStringValue ( dataRow, Constants.CommentFieldNames.Text );
            comment.DiscussionId = GetIntegerValue ( dataRow, Constants.CommentFieldNames.DiscussionId );

            comment.EditType = EditType.Unchanged;
            return comment;
        }

        public static Comment MakeComment ( SPListItem listItem )
        {
            Comment comment = new Comment ( );

            comment.CreatedBy = GetUserValue ( listItem, Constants.CommentFieldNames.CreatedBy );
            comment.CreatedDate = GetDateTimeValue ( listItem, Constants.CommentFieldNames.CreatedDate );
            comment.Description = GetStringValue ( listItem, Constants.CommentFieldNames.Description );
            comment.Id = GetIntegerValue ( listItem, Constants.CommentFieldNames.ItemId );
            comment.IsNew = GetBooleanValue ( listItem, Constants.CommentFieldNames.IsNew );
            comment.ModifiedBy = GetUserValue ( listItem, Constants.CommentFieldNames.ModifiedBy );
            comment.ModifiedDate = GetDateTimeValue ( listItem, Constants.CommentFieldNames.ModifiedDate );
            comment.ServerRelativeUrl = GetStringValue ( listItem, Constants.CommentFieldNames.ServerRelativeUrl );
            comment.SiteCollectionId = GetGuidValue ( listItem, Constants.CommentFieldNames.SiteCollectionId );

            comment.Text = GetStringValue ( listItem, Constants.CommentFieldNames.Text );
            comment.DiscussionId = GetIntegerValue ( listItem, Constants.CommentFieldNames.DiscussionId );

            // attach attachments
            if ( comment != null && listItem.Folder != null )
            {
                foreach ( SPFile file in listItem.Folder.Files )
                {
                    comment.AttachmentList.Add ( MakeAttachment ( file ) );
                }
            }

            comment.EditType = EditType.Unchanged;
            return comment;
        }

        #endregion

        #region Make Discussions

        public static Discussion MakeDiscussion ( DataRow dataRow )
        {
            Discussion discussion = new Discussion ( );

            discussion.CreatedBy = GetUserValue ( dataRow, Constants.DiscussionFieldNames.CreatedBy );
            discussion.CreatedDate = GetDateTimeValue ( dataRow, Constants.DiscussionFieldNames.CreatedDate );
            discussion.Description = GetStringValue ( dataRow, Constants.DiscussionFieldNames.Description );
            discussion.Id = GetIntegerValue ( dataRow, Constants.DiscussionFieldNames.ItemId );
            discussion.IsNew = GetBooleanValue ( dataRow, Constants.DiscussionFieldNames.IsNew );
            discussion.ModifiedBy = GetUserValue ( dataRow, Constants.DiscussionFieldNames.ModifiedBy );
            discussion.ModifiedDate = GetDateTimeValue ( dataRow, Constants.DiscussionFieldNames.ModifiedDate );
            discussion.ServerRelativeUrl = GetStringValue ( dataRow, Constants.DiscussionFieldNames.ServerRelativeUrl );
            discussion.SiteCollectionId = GetGuidValue ( dataRow, Constants.DiscussionFieldNames.SiteCollectionId );
            discussion.Title = GetStringValue ( dataRow, Constants.DiscussionFieldNames.Title );

            discussion.Text = GetStringValue(dataRow, Constants.DiscussionFieldNames.Text);
            discussion.HTMLText = GetStringValue(dataRow, Constants.DiscussionFieldNames.HTMLText);

            discussion.EditType = EditType.Unchanged;
            return discussion;
        }

        public static Discussion MakeDiscussion ( SPListItem listItem )
        {
            Discussion discussion = new Discussion ( );

            discussion.CreatedBy = GetUserValue ( listItem, Constants.DiscussionFieldNames.CreatedBy );
            discussion.CreatedDate = GetDateTimeValue ( listItem, Constants.DiscussionFieldNames.CreatedDate );
            discussion.Description = GetStringValue ( listItem, Constants.DiscussionFieldNames.Description );
            discussion.Id = GetIntegerValue ( listItem, Constants.DiscussionFieldNames.ItemId );
            discussion.IsNew = GetBooleanValue ( listItem, Constants.DiscussionFieldNames.IsNew );
            discussion.ModifiedBy = GetUserValue ( listItem, Constants.DiscussionFieldNames.ModifiedBy );
            discussion.ModifiedDate = GetDateTimeValue ( listItem, Constants.DiscussionFieldNames.ModifiedDate );
            discussion.LastCommentDate = GetDateTimeValue ( listItem, Constants.DiscussionFieldNames.LastCommentDate );
            discussion.ServerRelativeUrl = GetStringValue ( listItem, Constants.DiscussionFieldNames.ServerRelativeUrl );
            discussion.SiteCollectionId = GetGuidValue ( listItem, Constants.DiscussionFieldNames.SiteCollectionId );
            discussion.Title = GetStringValue ( listItem, Constants.DiscussionFieldNames.Title );

            discussion.Text = GetStringValue(listItem, Constants.DiscussionFieldNames.Text);
            discussion.HTMLText = GetStringValue(listItem, Constants.DiscussionFieldNames.HTMLText);

            // attach attachments
            if ( discussion != null && listItem.Folder != null )
            {
                foreach ( SPFile file in listItem.Folder.Files )
                {
                    discussion.AttachmentList.Add ( MakeAttachment ( file ) );
                }
            }

            discussion.EditType = EditType.Unchanged;
            return discussion;
        }

        #endregion

        #region Make Documents

        public static Document MakeDocumentFromFileItem ( SPListItem listItem )
        {
            Document document = new Document ( );

            document.IsFolder = false;
            document.Id = listItem.ID;
            document.CreatedDate = GetDateTimeValue ( listItem, "Created" );
            document.ModifiedDate = GetDateTimeValue ( listItem, "Modified" );
            document.Description = GetStringValue ( listItem, Constants.DocumentFieldNames.Description );
            document.ServerRelativeUrl = GetStringValue ( listItem, Constants.DocumentFieldNames.ServerRelativeUrl );
            document.SiteCollectionId = GetGuidValue ( listItem, Constants.DocumentFieldNames.SiteCollectionId );
            if ( listItem.File.Exists )
            {
                document.Title = listItem.File.Name;
                document.FileLength = listItem.File.Length;
                document.Url = listItem.File.Url;
                document.IconUrl = "/_layouts/images/" + listItem.File.IconUrl;
                document.Version = listItem.File.MajorVersion;
            }
            else
            {
                document.Title = GetStringValue ( listItem, Constants.DocumentFieldNames.FileLeafRef );
            }
            document.IsProjectPlan = GetBooleanValue ( listItem, Constants.DocumentFieldNames.IsProjectPlan );
            document.EditType = EditType.Unchanged;

            // populate created by & modified by users
            using ( SPWeb web = SPHelpers.GetWeb ( listItem.Web.Site.ID, listItem.Web.ServerRelativeUrl ) )
            {
                SPUser spUser = web.AllUsers.GetByID ( Convert.ToInt32 ( GetListOfStringsValue ( listItem, "Author" ) [ 0 ] ) );
                User createdBy = new User ( );
                createdBy.Login = spUser.LoginName;
                document.CreatedBy = createdBy;

                spUser = web.AllUsers.GetByID ( Convert.ToInt32 ( GetListOfStringsValue ( listItem, "Editor" ) [ 0 ] ) );
                User modifiedBy = new User ( );
                modifiedBy.Login = spUser.LoginName;
                document.ModifiedBy = modifiedBy;
            }

            return document;
        }

        public static Document MakeDocumentFromFolderItem ( SPListItem listItem )
        {
            Document document = new Document ( );

            document.IsFolder = true;
            document.Id = listItem.ID;
            document.Description = GetStringValue ( listItem, Constants.DocumentFieldNames.Description );
            document.ServerRelativeUrl = GetStringValue ( listItem, Constants.DocumentFieldNames.ServerRelativeUrl );
            document.SiteCollectionId = GetGuidValue ( listItem, Constants.DocumentFieldNames.SiteCollectionId );
            document.Title = listItem.Folder.Name;
            document.Url = listItem.Folder.Url;
            document.IconUrl = "/_layouts/images/Kiiro/icon-folder-closed.png";
            document.EditType = EditType.Unchanged;

            return document;
        }

        #endregion

        #region Make Users

        public static User MakeUser ( DataRow dataRow, Guid siteCollectionId, string serverRelativeUrl )
        {
            User user = new User ( );

            user.AddToAllProjects = GetBooleanValue ( dataRow, Constants.UserFieldNames.AddToAllProjects );
            user.CompanyName = GetStringValue ( dataRow, Constants.UserFieldNames.CompanyName ) ?? string.Empty;
            user.CreatedBy = GetUserValue ( dataRow, Constants.UserFieldNames.CreatedBy );
            user.CreatedDate = GetDateTimeValue ( dataRow, Constants.UserFieldNames.CreatedDate );
            user.Description = GetStringValue ( dataRow, Constants.UserFieldNames.Description );
            user.Email = GetStringValue ( dataRow, Constants.UserFieldNames.Email );
            user.FirstName = GetStringValue ( dataRow, Constants.UserFieldNames.FirstName );
            user.Id = GetIntegerValue ( dataRow, Constants.UserFieldNames.ItemId );
            user.IM = GetStringValue ( dataRow, Constants.UserFieldNames.IM );
            user.IMClient = GetStringValue ( dataRow, Constants.UserFieldNames.IMClient );
            user.IsADGroup = GetBooleanValue ( dataRow, Constants.UserFieldNames.IsADGroup );
            user.IsNonExplicitMember = GetBooleanValue ( dataRow, Constants.UserFieldNames.IsNonExplicitMember );
            user.IsFormsUser = GetBooleanValue ( dataRow, Constants.UserFieldNames.IsFormsUser );
            user.IsNew = GetBooleanValue ( dataRow, Constants.UserFieldNames.IsNew );
            user.IsSharePointAccount = GetBooleanValue ( dataRow, Constants.UserFieldNames.IsSharePointAccount );
            user.LastLoginTime = GetDateTimeValue ( dataRow, Constants.UserFieldNames.LastLoginTime );
            user.LastName = GetStringValue ( dataRow, Constants.UserFieldNames.LastName );
            user.Login = GetStringValue ( dataRow, Constants.UserFieldNames.Login );
            user.ManageProjectsOnly = GetBooleanValue ( dataRow, Constants.UserFieldNames.ManageProjects );
            user.ModifiedBy = GetUserValue ( dataRow, Constants.UserFieldNames.ModifiedBy );
            user.ModifiedDate = GetDateTimeValue ( dataRow, Constants.UserFieldNames.ModifiedDate );
            user.Password = GetStringValue ( dataRow, Constants.UserFieldNames.Password );
            user.PasswordSecurityQuestion = GetStringValue ( dataRow, Constants.UserFieldNames.PasswordSecurityQuestion );
            user.PasswordSecurityAnswer = GetStringValue ( dataRow, Constants.UserFieldNames.PasswordSecurityAnswer );
            user.PhoneNumber = GetStringValue ( dataRow, Constants.UserFieldNames.PhoneNumber );
            user.PictureUrl = GetStringValue ( dataRow, Constants.UserFieldNames.PictureUrl );
            user.ProjectIds = GetListOfIntsValue ( dataRow, Constants.UserFieldNames.ProjectIds );
            user.ReceiveEmailNotification = GetBooleanValue ( dataRow, Constants.UserFieldNames.ReceiveEmailNotification );
            user.ServerRelativeUrl = GetStringValue ( dataRow, Constants.UserFieldNames.ServerRelativeUrl );
            user.SiteCollectionId = GetGuidValue ( dataRow, Constants.UserFieldNames.SiteCollectionId );
            user.SPUserId = GetIntegerValue ( dataRow, Constants.UserFieldNames.SPUserId );
            user.StatusNote = GetStringValue ( dataRow, Constants.UserFieldNames.StatusNote ) ?? string.Empty;
            user.Title = GetStringValue ( dataRow, Constants.UserFieldNames.Title );

            string login = user.IsFormsUser ? "KiiroMembership:" + user.Login : user.Login;

            if ( user.SPUserId == default ( int ) )
                user.SPUserId = SPHelpers.GetSPUserId ( login, siteCollectionId, serverRelativeUrl );

            user.Groups = SPHelpers.GetUserGroups ( login, siteCollectionId, serverRelativeUrl );
            user.IsAdministrator = user.Groups.Contains ( KiiroGroup.PortalOwner ) && !user.ManageProjectsOnly;

            user.EditType = EditType.Unchanged;
            return user;
        }

        public static User MakeUser ( SPListItem listItem, Guid siteCollectionId, string serverRelativeUrl )
        {
            User user = new User ( );

            user.AddToAllProjects = GetBooleanValue ( listItem, Constants.UserFieldNames.AddToAllProjects );
            user.CompanyName = GetStringValue ( listItem, Constants.UserFieldNames.CompanyName ) ?? string.Empty;
            user.CreatedBy = GetUserValue ( listItem, Constants.UserFieldNames.CreatedBy );
            user.CreatedDate = GetDateTimeValue ( listItem, Constants.UserFieldNames.CreatedDate );
            user.Description = GetStringValue ( listItem, Constants.UserFieldNames.Description );
            user.Email = GetStringValue ( listItem, Constants.UserFieldNames.Email );
            user.FirstName = GetStringValue ( listItem, Constants.UserFieldNames.FirstName );
            user.Id = GetIntegerValue ( listItem, Constants.UserFieldNames.ItemId );
            user.IM = GetStringValue ( listItem, Constants.UserFieldNames.IM );
            user.IMClient = GetStringValue ( listItem, Constants.UserFieldNames.IMClient );
            user.IsADGroup = GetBooleanValue ( listItem, Constants.UserFieldNames.IsADGroup );
            user.IsNonExplicitMember = GetBooleanValue ( listItem, Constants.UserFieldNames.IsNonExplicitMember );
            user.IsFormsUser = GetBooleanValue ( listItem, Constants.UserFieldNames.IsFormsUser );
            user.IsNew = GetBooleanValue ( listItem, Constants.UserFieldNames.IsNew );
            user.IsSharePointAccount = GetBooleanValue ( listItem, Constants.UserFieldNames.IsSharePointAccount );
            user.LastLoginTime = GetDateTimeValue ( listItem, Constants.UserFieldNames.LastLoginTime );
            user.LastName = GetStringValue ( listItem, Constants.UserFieldNames.LastName );
            user.Login = GetStringValue ( listItem, Constants.UserFieldNames.Login );
            user.ManageProjectsOnly = GetBooleanValue ( listItem, Constants.UserFieldNames.ManageProjects );
            user.ModifiedBy = GetUserValue ( listItem, Constants.UserFieldNames.ModifiedBy );
            user.ModifiedDate = GetDateTimeValue ( listItem, Constants.UserFieldNames.ModifiedDate );
            user.Password = GetStringValue ( listItem, Constants.UserFieldNames.Password );
            user.PasswordSecurityQuestion = GetStringValue ( listItem, Constants.UserFieldNames.PasswordSecurityQuestion );
            user.PasswordSecurityAnswer = GetStringValue ( listItem, Constants.UserFieldNames.PasswordSecurityAnswer );
            user.PhoneNumber = GetStringValue ( listItem, Constants.UserFieldNames.PhoneNumber );
            user.PictureUrl = GetStringValue ( listItem, Constants.UserFieldNames.PictureUrl );
            user.ProjectIds = GetListOfIntsValue ( listItem, Constants.UserFieldNames.ProjectIds );
            user.ReceiveEmailNotification = GetBooleanValue ( listItem, Constants.UserFieldNames.ReceiveEmailNotification );
            user.ServerRelativeUrl = GetStringValue ( listItem, Constants.UserFieldNames.ServerRelativeUrl );
            user.SiteCollectionId = GetGuidValue ( listItem, Constants.UserFieldNames.SiteCollectionId );
            user.SPUserId = GetIntegerValue ( listItem, Constants.UserFieldNames.SPUserId );
            user.StatusNote = GetStringValue ( listItem, Constants.UserFieldNames.StatusNote ) ?? string.Empty;
            user.Title = GetStringValue ( listItem, Constants.UserFieldNames.Title );

            string login = user.IsFormsUser ? "KiiroMembership:" + user.Login : user.Login;

            if ( user.SPUserId == default ( int ) )
                user.SPUserId = SPHelpers.GetSPUserId ( login, siteCollectionId, serverRelativeUrl );

            user.Groups = SPHelpers.GetUserGroups ( login, siteCollectionId, serverRelativeUrl );
            user.IsAdministrator = user.Groups.Contains ( KiiroGroup.PortalOwner ) && !user.ManageProjectsOnly;

            user.EditType = EditType.Unchanged;
            return user;
        }

        #endregion

        #region Make Projects

        public static Project MakeProject ( DataRow dataRow )
        {
            Project project = new Project ( );

            project.ActualWork = GetFloatValue ( dataRow, Constants.ProjectFieldNames.ActualWork );
            project.CreatedBy = GetUserValue ( dataRow, Constants.ProjectFieldNames.CreatedBy );
            project.CreatedDate = GetDateTimeValue ( dataRow, Constants.ProjectFieldNames.CreatedDate );
            project.Description = GetStringValue ( dataRow, Constants.ProjectFieldNames.Description );
            project.DiscussionStats = GetListOfStringsValue ( dataRow, Constants.ProjectFieldNames.DiscussionStats );
            project.DocumentStats = GetListOfStringsValue ( dataRow, Constants.ProjectFieldNames.DocumentStats );
            project.EndDate = GetDateTimeValue ( dataRow, Constants.ProjectFieldNames.EndDate );
            project.Id = GetIntegerValue ( dataRow, Constants.ProjectFieldNames.ItemId );
            project.IsNew = GetBooleanValue ( dataRow, Constants.ProjectFieldNames.IsNew );
            project.IssueStats = GetListOfStringsValue ( dataRow, Constants.ProjectFieldNames.IssueStats );
            project.IsSynched = GetBooleanValue ( dataRow, Constants.ProjectFieldNames.IsSynched );
            project.ModifiedBy = GetUserValue ( dataRow, Constants.ProjectFieldNames.ModifiedBy );
            project.ModifiedDate = GetDateTimeValue ( dataRow, Constants.ProjectFieldNames.ModifiedDate );
            project.PlanDirty = GetBooleanValue ( dataRow, Constants.ProjectFieldNames.PlanDirty );
            project.ProjectedWork = GetFloatValue ( dataRow, Constants.ProjectFieldNames.ProjectedWork );
            project.ProjectManagerIds = GetListOfIntsValue ( dataRow, Constants.ProjectFieldNames.ProjectManagerIds );
            //project.ProjectPlanBytes= GetFloatValue ( dataRow, Constants.ProjectFieldNames.ProjectPlanBytes );
            project.ProjectPlanFileUrl = GetStringValue ( dataRow, Constants.ProjectFieldNames.ProjectPlanFileUrl );
            project.ProjectStatus = GetProjectStatusValue ( dataRow, Constants.ProjectFieldNames.ProjectStatus );
            project.ServerRelativeUrl = GetStringValue ( dataRow, Constants.ProjectFieldNames.ServerRelativeUrl );
            project.ServerRelativeWebUrl = GetStringValue ( dataRow, Constants.ProjectFieldNames.ServerRelativeWebUrl );
            project.SiteCollectionId = GetGuidValue ( dataRow, Constants.ProjectFieldNames.SiteCollectionId );
            project.StartDate = GetDateTimeValue ( dataRow, Constants.ProjectFieldNames.StartDate );
            project.SummaryNote = GetStringValue ( dataRow, Constants.ProjectFieldNames.SummaryNote );
            project.TasksDirty = GetBooleanValue ( dataRow, Constants.ProjectFieldNames.TasksDirty );
            project.TaskStats = GetListOfStringsValue ( dataRow, Constants.ProjectFieldNames.TaskStats );
            project.TimeMetric = GetTimeMetricValue ( dataRow, Constants.ProjectFieldNames.TimeMetric );
            project.Title = GetStringValue ( dataRow, Constants.ProjectFieldNames.Title );
            project.TotalWork = GetFloatValue ( dataRow, Constants.ProjectFieldNames.TotalWork );
            project.LastUpdatedSummaryNote = GetStringValue ( dataRow, Constants.ProjectFieldNames.LastUpdatedSummaryNote );
            project.IsWPSandboxActivated = GetBooleanValue ( dataRow, Constants.ProjectFieldNames.IsWPSandboxActivated );
            project.WPSandboxNavText = GetStringValue ( dataRow, Constants.ProjectFieldNames.WPSandboxNavText );

            project.EditType = EditType.Unchanged;
            return project;
        }

        public static Project MakeProject ( SPListItem listItem )
        {
            Project project = new Project ( );

            project.ActualWork = GetFloatValue ( listItem, Constants.ProjectFieldNames.ActualWork );
            project.CreatedBy = GetUserValue ( listItem, Constants.ProjectFieldNames.CreatedBy );
            project.CreatedDate = GetDateTimeValue ( listItem, Constants.ProjectFieldNames.CreatedDate );
            project.Description = GetStringValue ( listItem, Constants.ProjectFieldNames.Description );
            project.DiscussionStats = GetListOfStringsValue ( listItem, Constants.ProjectFieldNames.DiscussionStats );
            project.DocumentStats = GetListOfStringsValue ( listItem, Constants.ProjectFieldNames.DocumentStats );
            project.EndDate = GetDateTimeValue ( listItem, Constants.ProjectFieldNames.EndDate );
            project.Id = GetIntegerValue ( listItem, Constants.ProjectFieldNames.ItemId );
            project.IsNew = GetBooleanValue ( listItem, Constants.ProjectFieldNames.IsNew );
            project.IssueStats = GetListOfStringsValue ( listItem, Constants.ProjectFieldNames.IssueStats );
            project.IsSynched = GetBooleanValue ( listItem, Constants.ProjectFieldNames.IsSynched );
            project.ModifiedBy = GetUserValue ( listItem, Constants.ProjectFieldNames.ModifiedBy );
            project.ModifiedDate = GetDateTimeValue ( listItem, Constants.ProjectFieldNames.ModifiedDate );
            project.PlanDirty = GetBooleanValue ( listItem, Constants.ProjectFieldNames.PlanDirty );
            project.ProjectedWork = GetFloatValue ( listItem, Constants.ProjectFieldNames.ProjectedWork );
            project.ProjectManagerIds = GetListOfIntsValue ( listItem, Constants.ProjectFieldNames.ProjectManagerIds );
            //project.ProjectPlanBytes= GetFloatValue ( listItem, Constants.ProjectFieldNames.ProjectPlanBytes );
            project.ProjectPlanFileUrl = GetStringValue ( listItem, Constants.ProjectFieldNames.ProjectPlanFileUrl );
            project.ProjectStatus = GetProjectStatusValue ( listItem, Constants.ProjectFieldNames.ProjectStatus );
            project.ServerRelativeUrl = GetStringValue ( listItem, Constants.ProjectFieldNames.ServerRelativeUrl );
            project.ServerRelativeWebUrl = GetStringValue ( listItem, Constants.ProjectFieldNames.ServerRelativeWebUrl );
            project.SiteCollectionId = GetGuidValue ( listItem, Constants.ProjectFieldNames.SiteCollectionId );
            project.StartDate = GetDateTimeValue ( listItem, Constants.ProjectFieldNames.StartDate );
            project.SummaryNote = GetStringValue ( listItem, Constants.ProjectFieldNames.SummaryNote );
            project.TasksDirty = GetBooleanValue ( listItem, Constants.ProjectFieldNames.TasksDirty );
            project.TaskStats = GetListOfStringsValue ( listItem, Constants.ProjectFieldNames.TaskStats );
            project.TimeMetric = GetTimeMetricValue ( listItem, Constants.ProjectFieldNames.TimeMetric );
            project.Title = GetStringValue ( listItem, Constants.ProjectFieldNames.Title );
            project.TotalWork = GetFloatValue ( listItem, Constants.ProjectFieldNames.TotalWork );
            project.LastUpdatedSummaryNote = GetStringValue ( listItem, Constants.ProjectFieldNames.LastUpdatedSummaryNote );
            project.IsWPSandboxActivated = GetBooleanValue ( listItem, Constants.ProjectFieldNames.IsWPSandboxActivated );
            project.WPSandboxNavText = GetStringValue ( listItem, Constants.ProjectFieldNames.WPSandboxNavText );

            project.EditType = EditType.Unchanged;
            return project;
        }

        #endregion

        #region Make Setup

        public static Setup MakeSetup ( DataRow dataRow )
        {
            Setup setup = new Setup ( );

            setup.CreatedBy = GetUserValue ( dataRow, Constants.SetupFieldNames.CreatedBy );
            setup.CreatedDate = GetDateTimeValue ( dataRow, Constants.SetupFieldNames.CreatedDate );
            setup.Description = GetStringValue ( dataRow, Constants.SetupFieldNames.Description );
            setup.Id = GetIntegerValue ( dataRow, Constants.SetupFieldNames.ItemId );
            setup.ModifiedBy = GetUserValue ( dataRow, Constants.SetupFieldNames.ModifiedBy );
            setup.ModifiedDate = GetDateTimeValue ( dataRow, Constants.SetupFieldNames.ModifiedDate );
            setup.ServerRelativeUrl = GetStringValue ( dataRow, Constants.SetupFieldNames.ServerRelativeUrl );
            setup.SiteCollectionId = GetGuidValue ( dataRow, Constants.SetupFieldNames.SiteCollectionId );
            setup.Title = GetStringValue ( dataRow, Constants.SetupFieldNames.Title );

            setup.SiteName = GetStringValue ( dataRow, Constants.SetupFieldNames.SiteName );
            setup.SendEmailUpdates = GetBooleanValue ( dataRow, Constants.SetupFieldNames.SendEmailUpdates );
            setup.AllowEmailReplies = GetBooleanValue ( dataRow, Constants.SetupFieldNames.AllowEmailReplies );
            setup.EmailFromAddress = GetStringValue ( dataRow, Constants.SetupFieldNames.EmailFromAddress );
            setup.SMTPInfo = GetStringValue ( dataRow, Constants.SetupFieldNames.SMTPInfo );
            setup.POPInfo = GetStringValue ( dataRow, Constants.SetupFieldNames.POPInfo );
            setup.POPEmail = GetStringValue ( dataRow, Constants.SetupFieldNames.POPEmail );
            setup.LicenseKey = GetStringValue ( dataRow, Constants.SetupFieldNames.LicenseKey );
            setup.LogoUrl = GetStringValue ( dataRow, Constants.SetupFieldNames.LogoUrl );
            setup.SyncIntervalHours = GetFloatValue ( dataRow, Constants.SetupFieldNames.SyncIntervalHours );
            setup.MSProjectIntegration = GetBooleanValue ( dataRow, Constants.SetupFieldNames.MSProjectIntegration );
            setup.MinMSProjectPluginVer = GetVersionValue ( dataRow, Constants.SetupFieldNames.MinMSProjectPluginVer );
            setup.HoursPerDay = GetDoubleValue ( dataRow, Constants.SetupFieldNames.HoursPerDay );
            setup.IsWPSandboxActivated = GetBooleanValue ( dataRow, Constants.SetupFieldNames.IsWPSandboxActivated );
            setup.WPSandboxNavText = GetStringValue ( dataRow, Constants.SetupFieldNames.WPSandboxNavText );

            setup.EditType = EditType.Unchanged;
            return setup;
        }

        public static Setup MakeSetup ( SPListItem listItem )
        {
            Setup setup = new Setup ( );

            setup.CreatedBy = GetUserValue ( listItem, Constants.SetupFieldNames.CreatedBy );
            setup.CreatedDate = GetDateTimeValue ( listItem, Constants.SetupFieldNames.CreatedDate );
            setup.Description = GetStringValue ( listItem, Constants.SetupFieldNames.Description );
            setup.Id = GetIntegerValue ( listItem, Constants.SetupFieldNames.ItemId );
            setup.ModifiedBy = GetUserValue ( listItem, Constants.SetupFieldNames.ModifiedBy );
            setup.ModifiedDate = GetDateTimeValue ( listItem, Constants.SetupFieldNames.ModifiedDate );
            setup.ServerRelativeUrl = GetStringValue ( listItem, Constants.SetupFieldNames.ServerRelativeUrl );
            setup.SiteCollectionId = GetGuidValue ( listItem, Constants.SetupFieldNames.SiteCollectionId );
            setup.Title = GetStringValue ( listItem, Constants.SetupFieldNames.Title );

            setup.SiteName = GetStringValue ( listItem, Constants.SetupFieldNames.SiteName );
            setup.SendEmailUpdates = GetBooleanValue ( listItem, Constants.SetupFieldNames.SendEmailUpdates );
            setup.AllowEmailReplies = GetBooleanValue ( listItem, Constants.SetupFieldNames.AllowEmailReplies );
            setup.EmailFromAddress = GetStringValue ( listItem, Constants.SetupFieldNames.EmailFromAddress );
            setup.SMTPInfo = GetStringValue ( listItem, Constants.SetupFieldNames.SMTPInfo );
            setup.POPInfo = GetStringValue ( listItem, Constants.SetupFieldNames.POPInfo );
            setup.POPEmail = GetStringValue ( listItem, Constants.SetupFieldNames.POPEmail );
            setup.POPPassword = GetStringValueFromPropertyBag ( listItem, Constants.SetupFieldNames.POPPassword );
            setup.LicenseKey = GetStringValue ( listItem, Constants.SetupFieldNames.LicenseKey );
            setup.LogoUrl = GetStringValue ( listItem, Constants.SetupFieldNames.LogoUrl );
            setup.SyncIntervalHours = GetFloatValue ( listItem, Constants.SetupFieldNames.SyncIntervalHours );
            setup.MSProjectIntegration = GetBooleanValue ( listItem, Constants.SetupFieldNames.MSProjectIntegration );
            setup.MinMSProjectPluginVer = GetVersionValue ( listItem, Constants.SetupFieldNames.MinMSProjectPluginVer );
            setup.HoursPerDay = GetDoubleValue ( listItem, Constants.SetupFieldNames.HoursPerDay );
            setup.IsWPSandboxActivated = GetBooleanValue ( listItem, Constants.SetupFieldNames.IsWPSandboxActivated );
            setup.WPSandboxNavText = GetStringValue ( listItem, Constants.SetupFieldNames.WPSandboxNavText );

            setup.EditType = EditType.Unchanged;
            return setup;
        }

        #endregion

        #region Make Teams

        public static TeamMember MakeTeam ( DataRow dataRow )
        {
            TeamMember teamMember = new TeamMember ( );

            teamMember.CreatedBy = GetUserValue ( dataRow, Constants.TeamMemberFieldNames.CreatedBy );
            teamMember.CreatedDate = GetDateTimeValue ( dataRow, Constants.TeamMemberFieldNames.CreatedDate );
            teamMember.Description = GetStringValue ( dataRow, Constants.TeamMemberFieldNames.Description );
            teamMember.Id = GetIntegerValue ( dataRow, Constants.TeamMemberFieldNames.ItemId );
            teamMember.IsNew = GetBooleanValue ( dataRow, Constants.TeamMemberFieldNames.IsNew );
            teamMember.ModifiedBy = GetUserValue ( dataRow, Constants.TeamMemberFieldNames.ModifiedBy );
            teamMember.ModifiedDate = GetDateTimeValue ( dataRow, Constants.TeamMemberFieldNames.ModifiedDate );
            teamMember.ServerRelativeUrl = GetStringValue ( dataRow, Constants.TeamMemberFieldNames.ServerRelativeUrl );
            teamMember.SiteCollectionId = GetGuidValue ( dataRow, Constants.TeamMemberFieldNames.SiteCollectionId );
            teamMember.Title = GetStringValue ( dataRow, Constants.TeamMemberFieldNames.Title );

            teamMember.UserId = GetIntegerValue ( dataRow, Constants.TeamMemberFieldNames.UserId );
            teamMember.RoleOnProject = GetStringValue ( dataRow, Constants.TeamMemberFieldNames.RoleOnProject );
            teamMember.IsProjectManager = GetBooleanValue ( dataRow, Constants.TeamMemberFieldNames.IsProjectManager );

            teamMember.EditType = EditType.Unchanged;
            return teamMember;
        }

        public static TeamMember MakeTeam ( SPListItem listItem )
        {
            TeamMember teamMember = new TeamMember ( );

            teamMember.CreatedBy = GetUserValue ( listItem, Constants.TeamMemberFieldNames.CreatedBy );
            teamMember.CreatedDate = GetDateTimeValue ( listItem, Constants.TeamMemberFieldNames.CreatedDate );
            teamMember.Description = GetStringValue ( listItem, Constants.TeamMemberFieldNames.Description );
            teamMember.Id = GetIntegerValue ( listItem, Constants.TeamMemberFieldNames.ItemId );
            teamMember.IsNew = GetBooleanValue ( listItem, Constants.TeamMemberFieldNames.IsNew );
            teamMember.ModifiedBy = GetUserValue ( listItem, Constants.TeamMemberFieldNames.ModifiedBy );
            teamMember.ModifiedDate = GetDateTimeValue ( listItem, Constants.TeamMemberFieldNames.ModifiedDate );
            teamMember.ServerRelativeUrl = GetStringValue ( listItem, Constants.TeamMemberFieldNames.ServerRelativeUrl );
            teamMember.SiteCollectionId = GetGuidValue ( listItem, Constants.TeamMemberFieldNames.SiteCollectionId );
            teamMember.Title = GetStringValue ( listItem, Constants.TeamMemberFieldNames.Title );

            teamMember.UserId = GetIntegerValue ( listItem, Constants.TeamMemberFieldNames.UserId );
            teamMember.RoleOnProject = GetStringValue ( listItem, Constants.TeamMemberFieldNames.RoleOnProject );
            teamMember.IsProjectManager = GetBooleanValue ( listItem, Constants.TeamMemberFieldNames.IsProjectManager );

            teamMember.EditType = EditType.Unchanged;
            return teamMember;
        }

        #endregion

        #region Make Work

        public static Work MakeWork ( DataRow dataRow )
        {
            Work work = new Work ( );
            work.CreatedBy = GetUserValue ( dataRow, Constants.WorkFieldNames.CreatedBy );
            work.CreatedDate = GetDateTimeValue ( dataRow, Constants.WorkFieldNames.CreatedDate );
            work.Description = GetStringValue ( dataRow, Constants.WorkFieldNames.Description );
            //work.Id = GetIntegerValue(dataRow, Constants.WorkFieldNames.ItemId);
            work.Id = GetIntegerValue ( dataRow, "ID" );
            work.IsNew = GetBooleanValue ( dataRow, Constants.WorkFieldNames.IsNew );
            work.ModifiedBy = GetUserValue ( dataRow, Constants.WorkFieldNames.ModifiedBy );
            work.ModifiedDate = GetDateTimeValue ( dataRow, Constants.WorkFieldNames.ModifiedDate );
            work.ServerRelativeUrl = GetStringValue ( dataRow, Constants.WorkFieldNames.ServerRelativeUrl );
            work.SiteCollectionId = GetGuidValue ( dataRow, Constants.WorkFieldNames.SiteCollectionId );
            work.Title = GetStringValue ( dataRow, Constants.WorkFieldNames.Title );


            work.StartDate = GetDateTimeValue ( dataRow, Constants.WorkFieldNames.StartDate );
            work.EndDate = GetDateTimeValue ( dataRow, Constants.WorkFieldNames.EndDate );
            work.AssignedWork = GetFloatValue ( dataRow, Constants.WorkFieldNames.AssignedWork );
            work.StatusNote = GetStringValue ( dataRow, Constants.WorkFieldNames.StatusNote );
            work.AssignedToList = GetListOfIntsValue ( dataRow, Constants.WorkFieldNames.AssignedToList );
            work.ParentTasks = GetStringValue ( dataRow, Constants.WorkFieldNames.ParentTasks );
            work.IsHighPriority = GetBooleanValue ( dataRow, Constants.WorkFieldNames.IsHighPriority );
            work.WorkItemType = GetWorkTypeValue ( dataRow, Constants.WorkFieldNames.WorkItemType );
            work.Status = GetStatusTypeValue ( dataRow, Constants.WorkFieldNames.Status );
            work.IsLate = GetBooleanValue ( dataRow, Constants.WorkFieldNames.IsLate );
            work.IsSlipping = GetBooleanValue ( dataRow, Constants.WorkFieldNames.IsSlipping );
            work.IsFromProjectPlan = GetBooleanValue ( dataRow, Constants.WorkFieldNames.IsFromProjectPlan );
            work.IsDirty = GetBooleanValue ( dataRow, Constants.WorkFieldNames.IsDirty );
            work.PercentageComplete = GetFloatValue ( dataRow, Constants.WorkFieldNames.PercentageComplete );
            work.PlanId = GetIntegerValue ( dataRow, Constants.WorkFieldNames.PlanId );

            work.MembersEmail = GetStringValue ( dataRow, Constants.WorkFieldNames.MembersEmail );
            work.ProjectManagersEmail = GetStringValue ( dataRow, Constants.WorkFieldNames.ProjectManagersEmail );

            work.EditType = EditType.Unchanged;
            return work;
        }

        public static Work MakeWork ( SPListItem listItem )
        {
            Work work = new Work ( );

            work.CreatedBy = GetUserValue ( listItem, Constants.WorkFieldNames.CreatedBy );
            work.CreatedDate = GetDateTimeValue ( listItem, Constants.WorkFieldNames.CreatedDate );
            work.Description = GetStringValue ( listItem, Constants.WorkFieldNames.Description );
            work.Id = GetIntegerValue ( listItem, Constants.WorkFieldNames.ItemId );
            work.IsNew = GetBooleanValue ( listItem, Constants.WorkFieldNames.IsNew );
            work.ModifiedBy = GetUserValue ( listItem, Constants.WorkFieldNames.ModifiedBy );
            work.ModifiedDate = GetDateTimeValue ( listItem, Constants.WorkFieldNames.ModifiedDate );
            work.ServerRelativeUrl = GetStringValue ( listItem, Constants.WorkFieldNames.ServerRelativeUrl );
            work.SiteCollectionId = GetGuidValue ( listItem, Constants.WorkFieldNames.SiteCollectionId );
            work.Title = GetStringValue ( listItem, Constants.WorkFieldNames.Title );


            work.StartDate = GetDateTimeValue ( listItem, Constants.WorkFieldNames.StartDate );
            work.EndDate = GetDateTimeValue ( listItem, Constants.WorkFieldNames.EndDate );
            work.AssignedWork = GetFloatValue ( listItem, Constants.WorkFieldNames.AssignedWork );
            work.StatusNote = GetStringValue ( listItem, Constants.WorkFieldNames.StatusNote );
            work.AssignedToList = GetListOfIntsValue ( listItem, Constants.WorkFieldNames.AssignedToList );
            work.ParentTasks = GetStringValue ( listItem, Constants.WorkFieldNames.ParentTasks );
            work.IsHighPriority = GetBooleanValue ( listItem, Constants.WorkFieldNames.IsHighPriority );
            work.WorkItemType = GetWorkTypeValue ( listItem, Constants.WorkFieldNames.WorkItemType );
            work.Status = GetStatusTypeValue ( listItem, Constants.WorkFieldNames.Status );
            work.IsLate = GetBooleanValue ( listItem, Constants.WorkFieldNames.IsLate );
            work.IsSlipping = GetBooleanValue ( listItem, Constants.WorkFieldNames.IsSlipping );
            work.IsFromProjectPlan = GetBooleanValue ( listItem, Constants.WorkFieldNames.IsFromProjectPlan );
            work.IsDirty = GetBooleanValue ( listItem, Constants.WorkFieldNames.IsDirty );
            work.PercentageComplete = GetFloatValue ( listItem, Constants.WorkFieldNames.PercentageComplete );
            work.PlanId = GetIntegerValue ( listItem, Constants.WorkFieldNames.PlanId );

            // attach attachments
            if ( work != null && listItem.Folder != null )
            {
                foreach ( SPFile file in listItem.Folder.Files )
                {
                    work.AttachmentList.Add ( MakeAttachment ( file ) );
                }
            }

            work.MembersEmail = GetStringValue ( listItem, Constants.WorkFieldNames.MembersEmail );
            work.ProjectManagersEmail = GetStringValue ( listItem, Constants.WorkFieldNames.ProjectManagersEmail );

            work.EditType = EditType.Unchanged;
            return work;
        }

        #endregion

        #region Make ActivityHistory

        public static ActivityHistory MakeActivityHistory ( DataRow dataRow )
        {
            ActivityHistory activityHistory = new ActivityHistory ( );

            activityHistory.CreatedBy = GetUserValue ( dataRow, Constants.ActivityHistoryFieldNames.CreatedBy );
            activityHistory.CreatedDate = GetDateTimeValue ( dataRow, Constants.ActivityHistoryFieldNames.CreatedDate );
            activityHistory.Description = GetStringValue ( dataRow, Constants.ActivityHistoryFieldNames.Description );
            activityHistory.Id = GetIntegerValue ( dataRow, Constants.ActivityHistoryFieldNames.ItemId );
            activityHistory.IsNew = GetBooleanValue ( dataRow, Constants.ActivityHistoryFieldNames.IsNew );
            activityHistory.ModifiedBy = GetUserValue ( dataRow, Constants.ActivityHistoryFieldNames.ModifiedBy );
            activityHistory.ModifiedDate = GetDateTimeValue ( dataRow, Constants.ActivityHistoryFieldNames.ModifiedDate );
            activityHistory.ServerRelativeUrl = GetStringValue ( dataRow, Constants.ActivityHistoryFieldNames.ServerRelativeUrl );
            activityHistory.SiteCollectionId = GetGuidValue ( dataRow, Constants.WorkFieldNames.SiteCollectionId );
            activityHistory.Title = GetStringValue ( dataRow, Constants.ActivityHistoryFieldNames.Title );

            activityHistory.ActivityReferenceUrl = GetStringValue ( dataRow, Constants.ActivityHistoryFieldNames.ActivityReferenceUrl );
            activityHistory.ActivityItemType = GetItemTypeValue ( dataRow, Constants.ActivityHistoryFieldNames.ActivityItemType );
            activityHistory.EventType = GetEventTypeValue ( dataRow, Constants.ActivityHistoryFieldNames.EventType );

            GetReferenceItem ( activityHistory );

            activityHistory.EditType = EditType.Unchanged;
            return activityHistory;
        }

        public static ActivityHistory MakeActivityHistory ( SPListItem listItem )
        {
            ActivityHistory activityHistory = new ActivityHistory ( );

            activityHistory.CreatedBy = GetUserValue ( listItem, Constants.ActivityHistoryFieldNames.CreatedBy );
            activityHistory.CreatedDate = GetDateTimeValue ( listItem, Constants.ActivityHistoryFieldNames.CreatedDate );
            activityHistory.Description = GetStringValue ( listItem, Constants.ActivityHistoryFieldNames.Description );
            activityHistory.Id = GetIntegerValue ( listItem, Constants.ActivityHistoryFieldNames.ItemId );
            activityHistory.IsNew = GetBooleanValue ( listItem, Constants.ActivityHistoryFieldNames.IsNew );
            activityHistory.ModifiedBy = GetUserValue ( listItem, Constants.ActivityHistoryFieldNames.ModifiedBy );
            activityHistory.ModifiedDate = GetDateTimeValue ( listItem, Constants.ActivityHistoryFieldNames.ModifiedDate );
            activityHistory.ServerRelativeUrl = GetStringValue ( listItem, Constants.ActivityHistoryFieldNames.ServerRelativeUrl );
            activityHistory.SiteCollectionId = GetGuidValue ( listItem, Constants.WorkFieldNames.SiteCollectionId );
            activityHistory.Title = GetStringValue ( listItem, Constants.ActivityHistoryFieldNames.Title );

            activityHistory.ActivityReferenceUrl = GetStringValue ( listItem, Constants.ActivityHistoryFieldNames.ActivityReferenceUrl );
            activityHistory.ActivityItemType = GetItemTypeValue ( listItem, Constants.ActivityHistoryFieldNames.ActivityItemType );
            activityHistory.EventType = GetEventTypeValue ( listItem, Constants.ActivityHistoryFieldNames.EventType );

            GetReferenceItem ( activityHistory );

            activityHistory.EditType = EditType.Unchanged;
            return activityHistory;
        }

        private static void GetReferenceItem ( ActivityHistory activityHistory )
        {
            try
            {
                string serverRelativeWebUrl = SPHelpers.GetServerRelativeWebUrl ( activityHistory.SiteCollectionId, activityHistory.ServerRelativeUrl );
                using ( SPWeb web = SPHelpers.GetWeb ( activityHistory.SiteCollectionId, serverRelativeWebUrl ) )
                {
                    switch ( activityHistory.ActivityItemType )
                    {
                        case ItemType.Project:
                        case ItemType.ProjectPlan:
                            activityHistory.ReferencedItem = MakeProject ( web.GetListItem ( activityHistory.ActivityReferenceUrl ) );
                            break;
                        case ItemType.Comment:
                            activityHistory.ReferencedItem = MakeComment ( web.GetListItem ( activityHistory.ActivityReferenceUrl ) );
                            break;
                        case ItemType.Discussion:
                            activityHistory.ReferencedItem = MakeDiscussion ( web.GetListItem ( activityHistory.ActivityReferenceUrl ) );
                            break;
                        case ItemType.Document:
                            int docId = 0;
                            int.TryParse ( activityHistory.ActivityReferenceUrl, out docId );
                            SPListItem documentsListItem = web.Lists [ "Documents" ].GetItemById ( docId );

                            if ( documentsListItem != null && documentsListItem.File != null )
                            {
                                activityHistory.ReferencedItem = MakeDocumentFromFileItem ( documentsListItem );
                                activityHistory.ActivityReferenceUrl = documentsListItem.File.Url;
                            }
                            else
                                activityHistory.ReferencedItem = MakeDocumentFromFolderItem ( documentsListItem );
                            break;
                        case ItemType.Issue:
                        case ItemType.Task:
                            activityHistory.ReferencedItem = MakeWork ( web.GetListItem ( activityHistory.ActivityReferenceUrl ) ) as BaseEntity;
                            break;
                        case ItemType.User:
                            activityHistory.ReferencedItem = MakeUser ( web.GetListItem ( activityHistory.ActivityReferenceUrl ), activityHistory.SiteCollectionId, serverRelativeWebUrl );
                            break;
                        case ItemType.CustomItem:
                            activityHistory.ReferencedItem = MakeCustomItem ( web.GetListItem ( activityHistory.ActivityReferenceUrl ) );
                            break;
                        default:
                            break;
                    }
                }
            }
            catch { }
        }

        #endregion

        #region Make CustomItem

        public static CustomItem MakeCustomItem ( SPListItem listItem )
        {
            CustomItem customItem = new CustomItem ( );

            customItem.CreatedBy = GetMidoriUser ( listItem, Constants.CustomItemFieldNames.CreatedBy );
            customItem.CreatedDate = GetDateTimeValue ( listItem, Constants.CustomItemFieldNames.CreatedDate );
            customItem.Id = GetIntegerValue ( listItem, Constants.CustomItemFieldNames.Id );
            customItem.ModifiedBy = GetMidoriUser ( listItem, Constants.CustomItemFieldNames.ModifiedBy );
            customItem.ModifiedDate = GetDateTimeValue ( listItem, Constants.CustomItemFieldNames.ModifiedDate );
            customItem.Title = GetStringValue ( listItem, Constants.CustomItemFieldNames.Title );

            customItem.ServerRelativeUrl = string.Format ( "{0}/{1}", listItem.Web.ServerRelativeUrl, listItem.Url );
            customItem.SiteCollectionId = listItem.Web.Site.ID;

            customItem.Url = string.Format ( "{0}/DispForm.aspx?id={1}", listItem.ParentList.RootFolder.ServerRelativeUrl, listItem.ID );

            customItem.EditType = EditType.Unchanged;
            return customItem;
        }

        #endregion

        #region Make Attachment
        public static Attachment MakeAttachment ( SPFile file )
        {
            Attachment attachment = new Attachment ( );
            attachment.FileName = file.Name;
            attachment.ServerRelativeUrl = file.Url;
            attachment.IconUrl = "/_layouts/images/" + file.IconUrl;
            attachment.FileLength = file.Length;
            attachment.EditType = EditType.Unchanged;
            return attachment;
        }
        #endregion

        #region Make NavigationItem

        public static void MakeNavigationItem ( this NavigationItem navItem, SPListItem navListItem )
        {
            navItem.Id = navListItem.ID;
            navItem.Title = SPHelpers.ConvertHtmlToKiiroSafeText ( GetStringValue ( navListItem, Constants.NavigationFieldNames.Title ) );
            navItem.TargetUrl = GetStringValue ( navListItem, Constants.NavigationFieldNames.TargetUrl );
            navItem.SiteLevel = GetStringValue ( navListItem, Constants.NavigationFieldNames.SiteLevel );
            navItem.Sequence = GetIntegerValue ( navListItem, Constants.NavigationFieldNames.Sequence );
            navItem.IsVisible = GetBooleanValue ( navListItem, Constants.NavigationFieldNames.IsVisible );            
            navItem.GroupVisibility = GetListOfKiiroGroupsValue ( navListItem, Constants.NavigationFieldNames.GroupVisibility );
            navItem.PageHiLiteCollection = GetNavListOfStrings ( navListItem, Constants.NavigationFieldNames.PageHiLiteCollection );
            navItem.PageDisplayCollection = GetNavListOfStrings ( navListItem, Constants.NavigationFieldNames.PageDisplayCollection );
        }

        private static List<string> GetNavListOfStrings ( SPListItem listItem, string fieldName )
        {
            List<string> navList = new List<string>();
            string str = GetStringValue ( listItem, fieldName );
            if ( !string.IsNullOrEmpty ( str ) )
            {
                str = str.Replace ( "\r\n", ";#" );
                navList = FormattingHelpers.FieldTextToListOfStrings ( str );
            }
            return navList;
        }

        #endregion
    }
}

/*************************************************************************
 * 
 * $Log: /Internal Projects/Kiiro/Kiiro.Common/Utility/SPDataHelpers.cs $
 * 
 * 41    2/08/10 5:04p Camerons
 * 
 * 40    1/25/10 1:17p Camerons
 * 
 * 39    1/12/10 12:02p Camerons
 * 
 * 38    1/06/10 10:44p Camerons
 * 
 * 37    1/06/10 12:39p Camerons
 * 
 * 36    21/12/09 2:20p Adamw
 * 
 * 35    12/02/09 12:29p Stefanf
 * 
 * 34    26/11/09 10:35a Camerons
 * 
 * 33    24/11/09 10:55a Shafia
 * Discussion now stores the HTML format of the discussion text and uses
 * the WMD editor
 * 
 * 32    17/11/09 6:46p Camerons
 * 
 * 31    17/11/09 11:23a Camerons
 * 
 * 30    10/11/09 1:09p Camerons
 * 
 * 29    10/11/09 11:40a Camerons
 * 
 * 28    9/11/09 9:00p Camerons
 * 
 * 27    3/11/09 12:47p Camerons
 * 
 * 26    29/10/09 2:17p Camerons
 * 
 * 25    28/10/09 10:32p Camerons
 * 
 * 24    28/10/09 11:42a Camerons
 * 
 * 23    10/27/09 5:53p Adamw
 * accomodations for moving plan file to document library:
 * -moved saving of plan out of ProjectsDA and into DocumentModel -->
 * DocumentDA
 * -added call to save project plan file to document library from
 * ProjectsModel
 * -changed New/Edit Project pages to pass in Attachment collection
 * 
 * 22    7/10/09 5:14p Camerons
 * Case #281, #285: Update SPDataHelpers.MakeUser to take SiteCollectionId
 * and ServerRelativeUrl as params. Used to properly determine the group
 * memberships.
 * 
 * 21    30/09/09 9:10a Shafia
 * 
 * 20    29/09/09 2:19p Camerons
 * Implementing User.SPUserId
 * 
 * 19    29/09/09 1:22p Camerons
 * Implementing User.SPUserId
 * 
 * 18    29/09/09 12:40p Shafia
 * Implemented WebPart at project level
 * 
 * 17    28/09/09 3:38p Camerons
 * 
 * 16    23/09/09 4:46p Camerons
 * Fixed some old code dealing with User.ManageProjects
 * 
 * 15    22/09/09 6:03p Camerons
 * Code changes to support creating user on demand - version 1.1.x.x
 * 
 * 14    31/08/09 12:20p Shafia
 * Assign LastUpdatedSummaryNote a value
 * 
 * 13    17/08/09 10:38a Camerons
 * Added check-in comments section
 * 
 ************************************************************************/